﻿using FuzzySharp.Extractor;
using FuzzySharp.SimilarityRatio.Scorer.StrategySensitive;
using FuzzySharp.SimilarityRatio;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FuzzySharp;
using JiebaNet.Segmenter;
using System.Collections;

namespace ConsoleApp1;

// 安装NuGet包：Install-Package FuzzySharp
public class FuzzyMatcher
{
    /// <summary>
    /// 预处理中文，进行分词，去掉单字
    /// <br/>默认分词模式为 “精确模式”
    /// </summary>
    /// <param name="text"></param>
    /// <param name="cutAll">是否开启分词全模式</param>
    /// <returns></returns>
    public static string PreprocessChinese(string text,bool cutAll = false)
    {
        var segmenter = new JiebaSegmenter();
        return string.Join(" ", segmenter.Cut(text, cutAll)
            .Where(word => word.Length > 1) // 过滤单字
            .Select(word => word.ToLowerInvariant()));
    }

    /// <summary>
    /// 简单比例匹配(标准Levenshtein距离)（等效于fuzzywuzzy.ratio）
    /// </summary>
    /// <param name="s1"></param>
    /// <param name="s2"></param>
    /// <returns></returns>
    public static int Ratio(string s1, string s2)
    {
        return Fuzz.Ratio(s1, s2);
    }

    /// <summary>
    /// 最佳子串匹配(部分匹配)（等效于fuzzywuzzy.partial_ratio）
    /// </summary>
    /// <param name="s1"></param>
    /// <param name="s2"></param>
    /// <returns></returns>
    public static int PartialRatio(string s1, string s2)
    {
        return Fuzz.PartialRatio(s1, s2);
    }

    /// <summary>
    /// 词序无关匹配(词序无关的Levenshtein)（等效于fuzzywuzzy.token_sort_ratio）
    /// </summary>
    /// <param name="s1"></param>
    /// <param name="s2"></param>
    /// <returns></returns>
    public static int TokenSortRatio(string s1, string s2)
    {
        return Fuzz.TokenSortRatio(s1, s2);
    }

    /// <summary>
    /// 集合相似度优化版(带权重的词集匹配)（等效于fuzzywuzzy.token_set_ratio）
    /// </summary>
    /// <param name="s1"></param>
    /// <param name="s2"></param>
    /// <returns></returns>
    public static int TokenSetRatio(string s1, string s2)
    {
        return Fuzz.TokenSetRatio(s1, s2);
    }

	/// <summary>
	/// 获取TopN匹配结果（等效于fuzzywuzzy.extract）
	/// </summary>
	/// <param name="query">要比较的文本</param>
	/// <param name="choices">目标文本列表</param>
	/// <param name="cutoff">最低匹配阈值</param>
	/// <param name="limit">返回的数量</param>
	/// <returns></returns>
	public static List<ExtractedResult<string>> ExtractTop(
        string query,
        IEnumerable<string> choices,
        int cutoff = 50,
		int limit = 5)
    {
        return Process.ExtractTop(
            query,
            choices,
            cutoff: cutoff, 
            //cutoffInclusive: true,
            limit: limit
        ).ToList();
    }

}
